package com.sk.weichat.ui.me.redpacket;

import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.Observer;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.alipay.AliPayHelper;
import com.sk.weichat.alipay.PayResult;
import com.sk.weichat.bean.SendRedPacketBean;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.db.dao.ChatMessageDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseLoginActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.util.AnimationUtil;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.MaxTextTwoLengthFilter;
import com.sk.weichat.view.RedPacketDialog;
import com.sk.weichat.xmpp.listener.ChatMessageListener;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import okhttp3.Call;

/**
 * @Author: chenzl
 * @ClassName: SendRedPacketActivity1
 * @Description: 发红包
 * @CreateDate: 2019/10/9 11:46
 */
public class SendRedPacketActivity1 extends BaseLoginActivity implements View.OnClickListener {

    private ImageView imgLeft;
    private TextView tvRedpacketTips;
    private TextView tvRedpacketSum;
    private EditText editRedpackeSum;
    private TextView tvRedpacketUnit;
    private EditText editInputBlessing;
    private Button btnSendRedpacket;
    private String toUserId;
    private MutableLiveData<PayResult> alipayResult = new MutableLiveData<>();
    private SendRedPacketBean mSendRedPacketBean;
    private String mLoginUserId;
    private String mLoginNickName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_redpacket);
        getSupportActionBar().hide();
        toUserId = getIntent().getStringExtra("toUserId");
         mLoginUserId = coreManager.getSelf().getUserId();
         mLoginNickName = coreManager.getSelf().getNickName();
        initView();
    }

    private void initView(){
        imgLeft = findViewById(R.id.img_left);
        tvRedpacketTips = findViewById(R.id.tv_redpacket_tips);
        tvRedpacketSum = findViewById(R.id.tv_redpacket_sum);
        editRedpackeSum = findViewById(R.id.edit_redpacket_sum);
        tvRedpacketUnit = findViewById(R.id.tv_redpacket_unit);
        editInputBlessing = findViewById(R.id.edit_input_blessing);
        btnSendRedpacket = findViewById(R.id.btn_send_redpacket);
        editInputBlessing.setHint(coreManager.readConfigBean().getDefaultGreetings());
//        tvRedpacketTips.setAnimation(AnimationUtils.loadAnimation(this,R.anim.in_from_top));
        imgLeft.setOnClickListener(this);
        btnSendRedpacket.setOnClickListener(this);

        editRedpackeSum.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
                //删除.后面超过两位的数字
                if (s.toString().contains(".")) {
                    if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                        s = s.toString().subSequence(0,
                                s.toString().indexOf(".") + 3);
                        editRedpackeSum.setText(s);
                        editRedpackeSum.setSelection(s.length());
                    }
                }

                //如果.在起始位置,则起始位置自动补0
                if (s.toString().trim().equals(".")) {
                    s = "0" + s;
                    editRedpackeSum.setText(s);
                    editRedpackeSum.setSelection(2);
                }

                //如果起始位置为0并且第二位跟的不是".",则无法后续输入
                if (s.toString().startsWith("0")
                        && s.toString().trim().length() > 1) {
                    if (!s.toString().substring(1, 2).equals(".")) {
                        editRedpackeSum.setText(s.subSequence(0, 1));
                        editRedpackeSum.setSelection(1);
                        return;
                    }
                }
                //限制0.00输入
//                if (s.toString().startsWith("0")
//                        && s.toString().trim().length() > 3) {
//                    if (s.toString().substring(2,3).equals("0") && s.toString().substring(3,4).equals("0")) {
//                        editRedpackeSum.setText(s.subSequence(0,3));
//                        editRedpackeSum.setSelection(3);
//                        return;
//                    }
//                }
                if (!TextUtils.isEmpty(s.toString())&&Float.parseFloat(s.toString())>200){
                    tvRedpacketTips.setVisibility(View.VISIBLE);
                    tvRedpacketTips.setText("单个红包金额不可超过200元");

                    tvRedpacketSum.setTextColor(getResources().getColor(R.color.color_ff2626));
                    tvRedpacketUnit.setTextColor(getResources().getColor(R.color.color_ff2626));
                    editRedpackeSum.setTextColor(getResources().getColor(R.color.color_ff2626));
                }else if (!TextUtils.isEmpty(s.toString())&&Float.parseFloat(s.toString())==0){
                    tvRedpacketTips.setVisibility(View.VISIBLE);
                    tvRedpacketTips.setText("单个红包金额不可低于0.01元");
                    tvRedpacketSum.setTextColor(getResources().getColor(R.color.color_ff2626));
                    tvRedpacketUnit.setTextColor(getResources().getColor(R.color.color_ff2626));
                    editRedpackeSum.setTextColor(getResources().getColor(R.color.color_ff2626));
                }else {
                    tvRedpacketTips.setVisibility(View.GONE);
                    tvRedpacketSum.setTextColor(getResources().getColor(R.color.text_color_main));
                    tvRedpacketUnit.setTextColor(getResources().getColor(R.color.text_color_main));
                    editRedpackeSum.setTextColor(getResources().getColor(R.color.text_color_main));

                }
                if (!TextUtils.isEmpty(s.toString())){
                    //构造方法的字符格式这里如果小数不足2位,会以0补足.
                    DecimalFormat decimalFormat =new DecimalFormat("0.00");
                    String distanceString = decimalFormat.format(Float.valueOf(s.toString()));
                    btnSendRedpacket.setText(distanceString+"元 塞钱进红包");

                    if (Float.parseFloat(s.toString())>0&&Float.parseFloat(s.toString())<=200){
                        btnSendRedpacket.setEnabled(true);
                        btnSendRedpacket.setTextColor(getResources().getColor(R.color.color_FF4B4B));
                        btnSendRedpacket.setBackgroundResource(R.drawable.bg_dark_yellow_radius25);
                    }else {
                        btnSendRedpacket.setEnabled(false);
                        btnSendRedpacket.setTextColor(getResources().getColor(R.color.white));
                        btnSendRedpacket.setBackgroundResource(R.drawable.bg_gray_radius25);

                    }
                }else {
                    btnSendRedpacket.setText("0.00元 塞钱进红包");
                    btnSendRedpacket.setEnabled(false);
                    btnSendRedpacket.setTextColor(getResources().getColor(R.color.white));
                    btnSendRedpacket.setBackgroundResource(R.drawable.bg_gray_radius25);
                }
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }

        });
        editInputBlessing.setFilters(new InputFilter[]{new MaxTextTwoLengthFilter(24)});
        //支付宝支付返回
        alipayResult.observe(this, new Observer<PayResult>() {
            @Override
            public void onChanged(@Nullable PayResult payResult) {
                if (payResult.isResultFlag()) {
                    //支付成功
                    //ToastUtil.showToast(mContext, getString(R.string.pay_success));
                    Intent data = new Intent(SendRedPacketActivity1.this, ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("messageId",mSendRedPacketBean.getMessageId());
                    data.putExtras(bundle);
                    setResult(ChatActivity.REQUEST_CODE_SEND_RED_PT, data);
                    finish();
                } else if (payResult.getResultStatus().equals("6001")){
                    ToastUtil.showToast(mContext, getString(R.string.pay_cancel_failed));
                    //支付失败删除本地 红包消息记录
                    ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId,toUserId,mSendRedPacketBean.getMessageId());
                }else {
                    //支付失败删除本地 红包消息记录
                    ChatMessageDao.getInstance().deleteSingleChatMessage(mLoginUserId,toUserId,mSendRedPacketBean.getMessageId());
                    //失败
                    ToastUtil.showToast(mContext, getString(R.string.pay_failed));
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v==imgLeft){
            finish();
        }else if (v==btnSendRedpacket){
            RedPacketDialog  dialog = new RedPacketDialog(this, new RedPacketDialog.OnSendRedPacketListener() {
                @Override
                public void senRedPacketClick() {
                    sendRedPacket();
                }
            });
            dialog.show();
        }
    }

    /**
     * @author: czl
     * @description 发送红包 调起支付宝支付
     * @date: 2019/10/9 16:32
     */
    private void sendRedPacket(){
        if (!DialogHelper.isShowing()) {
            DialogHelper.showDefaulteMessageProgressDialog(this);
        }
        String greetings = TextUtils.isEmpty(editInputBlessing.getText().toString())?coreManager.readConfigBean().getDefaultGreetings():editInputBlessing.getText().toString();
        Map<String, String> params = new HashMap();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("type",  String.valueOf(1));
        params.put("money", editRedpackeSum.getText().toString());
        params.put("count", String.valueOf(1));
        params.put("greetings",greetings);
        params.put("toUserId",toUserId);

        HttpUtils.post().url(coreManager.getConfig().RED_PACKET_SEND)
                .params(params)
                .build()
                .execute(new BaseCallback<SendRedPacketBean>(SendRedPacketBean.class) {

                    @Override
                    public void onResponse(ObjectResult<SendRedPacketBean> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result.getResultCode()==1){
                            mSendRedPacketBean = result.getData();

                            ChatMessage message = new ChatMessage();
                            message.setType(XmppMessage.TYPE_RED);
                            message.setFromUserId(mLoginUserId);
                            message.setFromUserName(mLoginNickName);
                            message.setContent(greetings); // 祝福语
                            message.setFileSize(0); // 用FilePath来储存红包类型
                            message.setMessageState(ChatMessageListener.MESSAGE_SEND_ING);
                            message.setMySend(true);// 表示是自己发的
                            message.setPacketId(mSendRedPacketBean.getMessageId());// 消息id
                            message.setObjectId(mSendRedPacketBean.getRedId());// objectid  存红包id
                            message.setTimeSend(TimeUtils.sk_time_current_time());
                            //本地保存一条红包消息
                            ChatMessageDao.getInstance().saveNewSingleChatMessage(mLoginUserId,toUserId,message);
                            AliPayHelper.pay(mSendRedPacketBean.getOrderInfo(), SendRedPacketActivity1.this, alipayResult);
                        }else {
                            ToastUtil.showToast(SendRedPacketActivity1.this,result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.
                                dismissProgressDialog();
                        ToastUtil.showToast(SendRedPacketActivity1.this,e.toString());
                    }
                });
    }
}
